﻿CREATE PROCEDURE [dbo].[Text_Book_Create]
	@title NVARCHAR(MAX),
	@author NVARCHAR(MAX),
	@coverUrl NVARCHAR(256),
	@hashTag NVARCHAR(128)
AS
BEGIN
	SET @hashTag = RTRIM(LTRIM(LOWER(@hashTag)))
	SET @coverUrl = RTRIM(LTRIM(LOWER(@coverUrl)))

	IF EXISTS (SELECT * FROM [dbo].[text_BookTree] WHERE [HashTag] = @hashTag AND [Level] = 1)
	BEGIN
		RAISERROR ('HashTagExist',9,1)
		RETURN
	END

	BEGIN TRY
		BEGIN TRANSACTION

			DECLARE @bookId UNIQUEIDENTIFIER = NEWID()

			INSERT INTO [dbo].[text_Book]
								 ([BookId]
								 ,[Author]
								 ,[CoverUrl])
					 VALUES
								 (@bookId
								 ,@author
								 ,@coverUrl)

			EXEC	[dbo].[Text_BookTree_Add]
					@addParentTreeId = NULL,
					@bookId = @bookId,
					@hashTag = @hashTag,
					@isHead = 1,
					@published = 0,
					@text = @title,
					@currentId = NULL

			EXEC	[dbo].[Text_BookTree_Cache_Refresh]

		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT	@ErrorMessage = ERROR_MESSAGE(),
						@ErrorSeverity = ERROR_SEVERITY(),
						@ErrorState = ERROR_STATE();

		RAISERROR (
								@ErrorMessage, -- Message text.
								@ErrorSeverity, -- Severity.
								@ErrorState -- State.
							);

	END CATCH

END